/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package it.polimi.games.epkb.controller;

import it.polimi.games.epkb.controller.exceptions.NonexistentEntityException;
import it.polimi.games.epkb.controller.exceptions.PreexistingEntityException;
import it.polimi.games.epkb.entityClasses.Correlation;
import java.io.Serializable;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Query;
import javax.persistence.EntityNotFoundException;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;
import it.polimi.games.epkb.entityClasses.GpiKpi;
import javax.transaction.UserTransaction;

/**
 *
 * @author plebani
 */
public class CorrelationJpaController implements Serializable {


    public CorrelationJpaController(EntityManagerFactory emf) {
        this.utx = null;
        this.emf = emf;
    }

    public CorrelationJpaController(UserTransaction utx, EntityManagerFactory emf) {
        this.utx = utx;
        this.emf = emf;
    }
    private UserTransaction utx = null;
    private EntityManagerFactory emf = null;

    public EntityManager getEntityManager() {
        return emf.createEntityManager();
    }

    public void create(Correlation correlation) throws PreexistingEntityException, Exception {
        EntityManager em = null;
        try {
            em = getEntityManager();
            em.getTransaction().begin();
            GpiKpi idGPIKPI2 = correlation.getIdGPIKPI2();
            if (idGPIKPI2 != null) {
                idGPIKPI2 = em.getReference(idGPIKPI2.getClass(), idGPIKPI2.getId());
                correlation.setIdGPIKPI2(idGPIKPI2);
            }
            GpiKpi idGPIKPI1 = correlation.getIdGPIKPI1();
            if (idGPIKPI1 != null) {
                idGPIKPI1 = em.getReference(idGPIKPI1.getClass(), idGPIKPI1.getId());
                correlation.setIdGPIKPI1(idGPIKPI1);
            }
            em.persist(correlation);
            if (idGPIKPI2 != null) {
                idGPIKPI2.getCorrelationCollection().add(correlation);
                idGPIKPI2 = em.merge(idGPIKPI2);
            }
            if (idGPIKPI1 != null) {
                idGPIKPI1.getCorrelationCollection().add(correlation);
                idGPIKPI1 = em.merge(idGPIKPI1);
            }
            em.getTransaction().commit();
        } catch (Exception ex) {
            if (findCorrelation(correlation.getId()) != null) {
                throw new PreexistingEntityException("Correlation " + correlation + " already exists.", ex);
            }
            throw ex;
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public void edit(Correlation correlation) throws NonexistentEntityException, Exception {
        EntityManager em = null;
        try {
            em = getEntityManager();
            em.getTransaction().begin();
            Correlation persistentCorrelation = em.find(Correlation.class, correlation.getId());
            GpiKpi idGPIKPI2Old = persistentCorrelation.getIdGPIKPI2();
            GpiKpi idGPIKPI2New = correlation.getIdGPIKPI2();
            GpiKpi idGPIKPI1Old = persistentCorrelation.getIdGPIKPI1();
            GpiKpi idGPIKPI1New = correlation.getIdGPIKPI1();
            if (idGPIKPI2New != null) {
                idGPIKPI2New = em.getReference(idGPIKPI2New.getClass(), idGPIKPI2New.getId());
                correlation.setIdGPIKPI2(idGPIKPI2New);
            }
            if (idGPIKPI1New != null) {
                idGPIKPI1New = em.getReference(idGPIKPI1New.getClass(), idGPIKPI1New.getId());
                correlation.setIdGPIKPI1(idGPIKPI1New);
            }
            correlation = em.merge(correlation);
            if (idGPIKPI2Old != null && !idGPIKPI2Old.equals(idGPIKPI2New)) {
                idGPIKPI2Old.getCorrelationCollection().remove(correlation);
                idGPIKPI2Old = em.merge(idGPIKPI2Old);
            }
            if (idGPIKPI2New != null && !idGPIKPI2New.equals(idGPIKPI2Old)) {
                idGPIKPI2New.getCorrelationCollection().add(correlation);
                idGPIKPI2New = em.merge(idGPIKPI2New);
            }
            if (idGPIKPI1Old != null && !idGPIKPI1Old.equals(idGPIKPI1New)) {
                idGPIKPI1Old.getCorrelationCollection().remove(correlation);
                idGPIKPI1Old = em.merge(idGPIKPI1Old);
            }
            if (idGPIKPI1New != null && !idGPIKPI1New.equals(idGPIKPI1Old)) {
                idGPIKPI1New.getCorrelationCollection().add(correlation);
                idGPIKPI1New = em.merge(idGPIKPI1New);
            }
            em.getTransaction().commit();
        } catch (Exception ex) {
            String msg = ex.getLocalizedMessage();
            if (msg == null || msg.length() == 0) {
                String id = correlation.getId();
                if (findCorrelation(id) == null) {
                    throw new NonexistentEntityException("The correlation with id " + id + " no longer exists.");
                }
            }
            throw ex;
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public void destroy(String id) throws NonexistentEntityException {
        EntityManager em = null;
        try {
            em = getEntityManager();
            em.getTransaction().begin();
            Correlation correlation;
            try {
                correlation = em.getReference(Correlation.class, id);
                correlation.getId();
            } catch (EntityNotFoundException enfe) {
                throw new NonexistentEntityException("The correlation with id " + id + " no longer exists.", enfe);
            }
            GpiKpi idGPIKPI2 = correlation.getIdGPIKPI2();
            if (idGPIKPI2 != null) {
                idGPIKPI2.getCorrelationCollection().remove(correlation);
                idGPIKPI2 = em.merge(idGPIKPI2);
            }
            GpiKpi idGPIKPI1 = correlation.getIdGPIKPI1();
            if (idGPIKPI1 != null) {
                idGPIKPI1.getCorrelationCollection().remove(correlation);
                idGPIKPI1 = em.merge(idGPIKPI1);
            }
            em.remove(correlation);
            em.getTransaction().commit();
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public List<Correlation> findCorrelationEntities() {
        return findCorrelationEntities(true, -1, -1);
    }

    public List<Correlation> findCorrelationEntities(int maxResults, int firstResult) {
        return findCorrelationEntities(false, maxResults, firstResult);
    }

    private List<Correlation> findCorrelationEntities(boolean all, int maxResults, int firstResult) {
        EntityManager em = getEntityManager();
        try {
            CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
            cq.select(cq.from(Correlation.class));
            Query q = em.createQuery(cq);
            if (!all) {
                q.setMaxResults(maxResults);
                q.setFirstResult(firstResult);
            }
            return q.getResultList();
        } finally {
            em.close();
        }
    }

    public Correlation findCorrelation(String id) {
        EntityManager em = getEntityManager();
        try {
            return em.find(Correlation.class, id);
        } finally {
            em.close();
        }
    }

    public int getCorrelationCount() {
        EntityManager em = getEntityManager();
        try {
            CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
            Root<Correlation> rt = cq.from(Correlation.class);
            cq.select(em.getCriteriaBuilder().count(rt));
            Query q = em.createQuery(cq);
            return ((Long) q.getSingleResult()).intValue();
        } finally {
            em.close();
        }
    }
    
}
